function [output] = extractPtStruct
% Extract patient structure, together with numerics and demographics
% Structure will contain: 

% id                - patient's ID
% nicus             - number of ICU admissions and ICU IDs
% nhadm             - number of hosptial admission and correspondent IDs
% demographics      - demographics of the patient, including age and gender
%                           age
%                           ismale
% clinics           - clinical information:
%                           vsp: 1 is present
%                           lvef
%                           mort28d: 1 is death
% numerics          - data comprising HR, PP, Urine Output and Acid Lactic
%                           hr: Nx2
%                           pp: Nx2
%                           uo: Nx2
%                           la: Nx2
%

% load cohort with IDs and demographics information
fcohort = '../data/export_sepsis_cohort.csv';
[sid,hid,iid,gender,nage,nlos,nlvef,nmort28d,nvp] = ...
    textread(fcohort,'%d%d%d%c%n%n%d%d%d\n','headerlines',1,'delimiter',',');

% load numerics with IDs and icu admission ID
load('../data/cardiac_timeseries_13June.mat'); X = Data;
numerics = {'pulsep', 'hr', 'lactate', 'uo', 'map'};

[ptid] = unique(sid);
N = length(ptid);

% Perform pre-scan to look for repeated data
eliminateEntry = [];
for pt = ptid'
    ind = find(pt == sid); ind = ind(:);
    % check whether there are two ICU admissions with the same id
    if length(unique(iid(ind)))~=length(ind) 
        % Eliminate repetitive indices
        index = 1:length(ind);
        [~,ia,~] = unique(iid(ind));
        eliminateEntry = [eliminateEntry; ind(~ismember(index,ia))];
        disp('');
    end
end

diary(sprintf('../outputs/LogCreatePtStruct_%s.txt',date));
sid(eliminateEntry) = []; hid(eliminateEntry) = []; iid(eliminateEntry) = []; 
gender(eliminateEntry) = []; nage(eliminateEntry) = []; nlos(eliminateEntry) = []; 
nlvef(eliminateEntry) = []; nmort28d(eliminateEntry) = []; nvp(eliminateEntry) = [];
fprintf('\nFrom the pre-scanning, %d entries will be eliminated\n\n', ...
    length(eliminateEntry));

% create structure with as many entries as ptid
npt = 1;
ptstruct(N) = struct;
nCases = zeros(N,1);
for pt = ptid'
    ind = find(pt == sid); ind = ind(:);
    id = pt;
    nicus = [length(ind), iid(ind)']; 
    % check whether there are two ICU admissions with the same id
    if length(unique(iid(ind)))~=nicus(1) 
        fprintf('\nPatient %d with more icu admissions with the same index',pt);
        fprintf('\nCheck the following indices');
        ind
        nCases(npt) = 1;
    end
    nhadm = [length(unique(hid(ind))), hid(ind)'];
    ismale = strcmpi('M',gender(ind(1)));
    % check if there is something wrong with gender of the patient
    if strcmpi('M',gender(ind(1))) || strcmpi('F',gender(ind(1)))
        for j = ind'
            if ismale ~= strcmpi('M',gender(j))
                fprintf('\nPatient %d, gender is unconsistent',pt);
                fprintf('\nCheck the following indices');
                ind
                nCases(npt) = 1;
            end
        end
    else
        fprintf('\nPatient %d, gender is undefined',pt);
        fprintf('\nCheck the following indices');
        ind
        nCases(npt) = 1;
    end
    
    age = nage(ind)';
    los = nlos(ind)';
    clinics.lvef    = nlvef(ind)';
    clinics.vp      = nvp(ind)';
    clinics.mort28d = nmort28d(ind)';
    % ggg=[]; for i = 1 : length(X), if X{i,1}(1) == id, ggg = [ggg i]; end, end
    for j = 1 : length(ind)             % Loop over ICU admissions
        data{j} = struct(numerics{1},[],numerics{2},[],numerics{3},[],numerics{4},[],numerics{5},[]);
        FLAG = 0;
        for i = 1 : length(X)
            if sum([X{i,1}(1) X{i,1}(2)]==[pt iid(ind(j))]) == 2
                if FLAG                 % Make sure that there are no repetitions
                	fprintf('\nRepetition of session %d %d',pt,iid(ind(j)));
                else
                	FLAG = 1;
                    for n = 1 : 5
                        data{j} = setfield(data{j},numerics{n},X{i,n+1});
                    end
                end
            end
        end
    end
    ptstruct(npt).id = id; ptstruct(npt).ismale = ismale; ptstruct(npt).nhadm = nhadm;
    ptstruct(npt).nicus = nicus; ptstruct(npt).age = age; ptstruct(npt).los = los; 
    ptstruct(npt).clinics = clinics; ptstruct(npt).data = data;
    ptstruct(npt).isproblem = nCases(npt);
    
    npt = npt + 1;
    clear data;
    
    fprintf('\n\n **** %.2f%% Complete! **** ',npt/N*100)
end

fprintf('\n\n Number of Cases: %d',sum(nCases(:)));
diary off;
output = ptstruct;
save('../data/ptstruct2.mat','ptstruct');
